package org.sn.jdish.example.queue.ticket;

import org.sn.jdish.example.queue.CircleQueue;

/**
 * 循环队列-买票
 * 
 * @author snzigod@hotmail.com
 *
 */
public class TicketQueue {

	int maxSize = 10;
	CircleQueue queue = new CircleQueue(maxSize);
	int num = 0;
	boolean isAlive = true;

	public synchronized void producer() {
		if (queue.size < maxSize) {
			queue.enQueue(num++);
			System.out.println("等待买票数：" + num);
		}
	}

	public synchronized void consumer() {
		if (!queue.isEmpty()) {
			Object obj = queue.deQueue();
			System.out.println(obj);
			if (queue.isEmpty() && this.num >= 100) {
				this.isAlive = false;
			}
			this.notifyAll();
		}
	}

	public static void main(String[] args) {
		TicketQueue tQueue = new TicketQueue();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (tQueue.num < 100) {
					tQueue.producer();
				}
			}

		}).start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (tQueue.isAlive) {
					tQueue.consumer();
				}
			}

		}).start();
	}

}
